package com.sisucc.contractmanage.web.contractManage;

import com.sisucc.contractmanage.bean.ResultModel;
import com.sisucc.contractmanage.bean.accountInfo.AccountInfoBean;
import com.sisucc.contractmanage.bean.contractES.ContractEsBean;
import com.sisucc.contractmanage.bean.contractInfo.ContractInfoBean;
import com.sisucc.contractmanage.bean.staffInfo.StaffInfoBean;
import com.sisucc.contractmanage.constant.ConstantDataType;
import com.sisucc.contractmanage.constant.ReturnStatusCode;
import com.sisucc.contractmanage.dao.contractES.ContractEsBeanRepository;
import com.sisucc.contractmanage.dao.contractManage.ContractInfoRepository;
import com.sisucc.contractmanage.service.contractManageService.ContractManageService;
import com.sisucc.contractmanage.util.LocalDateTimeUtil;
import com.sisucc.contractmanage.util.PropertyUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import io.github.bluemiaomiao.service.FastdfsClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author linyuqi
 */
@Log4j2
@RestController
@Api(tags = "合同管理模块")
public class ContractManageController {

    @Autowired
    private FastdfsClientService fastdfsClientService;

    @Autowired
    private ContractManageService service;

    @Autowired
    private ContractInfoRepository contractInfoRepository;

    @Autowired
    private ContractEsBeanRepository contractEsBeanRepository;

    @PostMapping("/queryContractInfo")
    @ApiOperation(value = "动态查询合同信息", httpMethod = "POST")
    public ResultModel queryContractInfo(String staffCodeParam, String staffNameParam, String contractCodeParam, String contractNameParam,
                                         String startTimeParam, String endTimeParam, String accountStatusDropdownParam, String departDropdownParam,
                                         String contractTypeDropdownParam, String currentPage, String pageSize) throws ParseException {
        String accountStatusDropdown = accountStatusDropdownParam, departDropdown = departDropdownParam, contractTypeDropdown = contractTypeDropdownParam;
        if ("-1".equals(accountStatusDropdownParam)) {
            accountStatusDropdown = "";
        }
        if ("-1".equals(departDropdownParam)) {
            departDropdown = "";
        }
        if ("-1".equals(contractTypeDropdownParam)) {
            contractTypeDropdown = "";
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("staffCodeParam", staffCodeParam);
        params.put("staffNameParam", staffNameParam);
        params.put("contractCodeParam", contractCodeParam);
        params.put("contractNameParam", contractNameParam);
        params.put("startTimeParam", startTimeParam);
        params.put("endTimeParam", endTimeParam);
        params.put("accountStatusDropdownParam", accountStatusDropdown);
        params.put("departDropdownParam", departDropdown);
        params.put("contractTypeDropdownParam", contractTypeDropdown);
        params.put("currentPage", currentPage);
        params.put("pageSize", pageSize);
        log.info("动态查询合同信息的参数：" + params.toString());
        return service.queryContractInfo(params);
    }

    @PostMapping("/saveContractInfo")
    @ApiOperation(value = "保存合同信息", httpMethod = "POST")
    public ResultModel saveContractInfo(String contractName, String deadline, String contractTypeDropdownParam, MultipartFile contractFile,
                                        MultipartFile annexFile, HttpSession session) throws IOException, ParseException {
        ResultModel model = new ResultModel();
        String[] fileInfo = null;
        String[] annexInfo = null;
        try {
            fileInfo = fastdfsClientService.autoUpload(contractFile.getBytes(), "doc");
            log.info("fastdfs合同文件存储的分组名：" + fileInfo[0]);
            log.info("fastdfs合同文件存储的文件ID：" + fileInfo[1]);
        } catch (Exception e) {
            model.setStatusCode(ReturnStatusCode.FASTDFS_FILE_ERROR);
            model.setResultMessage(ReturnStatusCode.FASTDFS_FILE_ERROR_MESSAGE);
            log.info("fastdfs合同文件存储失败！");
            return model;
        }
        try {
            annexInfo = fastdfsClientService.autoUpload(annexFile.getBytes(), "zip");
            log.info("fastdfs合同附件存储的分组名：" + annexInfo[0]);
            log.info("fastdfs合同附件存储的文件ID：" + annexInfo[1]);
        } catch (Exception e) {
            model.setStatusCode(ReturnStatusCode.FASTDFS_ANNEX_ERROR);
            model.setResultMessage(ReturnStatusCode.FASTDFS_ANNEX_ERROR_MESSAGE);
            log.info("fastdfs合同附件存储文件失败！");
            return model;
        }

        AccountInfoBean accountInfo = (AccountInfoBean) session.getAttribute("currentAccountInfo");
        StaffInfoBean staffInfo = (StaffInfoBean) session.getAttribute("currentStaffInfo");
        String uuid = PropertyUtil.getUUID();
        String contractStatus = ConstantDataType.CONTRACT_ACTIVE_STATUS;
        LocalDateTime currentDateTime = PropertyUtil.getCurrentDateTime();
        String contractText = "";
        try {
            Document document = new Document();
            document.loadFromStream(contractFile.getInputStream(), FileFormat.Docx);
            contractText = document.getText();
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.DOC_EXTRACT_ERROR);
            model.setResultMessage(ReturnStatusCode.DOC_EXTRACT_ERROR_MESSAGE);
            log.info("doc文件解析失败---程序执行失败！");
            return model;
        }

        try {
            ContractEsBean contractEsBean = new ContractEsBean(uuid, contractName, contractStatus, contractText, staffInfo.getDepartName(), contractTypeDropdownParam,
                    staffInfo.getStaffCode(), staffInfo.getStaffName(), staffInfo.getDepartId(), LocalDateTimeUtil.getStringByLocalDateTime(currentDateTime));
            log.info("ES存储的对象信息为：" + contractEsBean.toString());
            contractEsBeanRepository.save(contractEsBean);
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ES_SAVE_ERROR);
            model.setResultMessage(ReturnStatusCode.ES_SAVE_ERROR_MESSAGE);
            log.info("ES存储合同信息失败---程序执行失败！");
            return model;
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("contractName", contractName);
        params.put("deadline", deadline);
        params.put("contractTypeDropdownParam", contractTypeDropdownParam);
        params.put("contractStatus", contractStatus);
        params.put("accountCode", accountInfo.getAccountCode());
        params.put("staffCode", staffInfo.getStaffCode());
        params.put("staffName", staffInfo.getStaffName());
        params.put("departId", staffInfo.getDepartId());
        params.put("departName", staffInfo.getDepartName());
        params.put("fileGroupName", fileInfo[0]);
        params.put("fileName", fileInfo[1]);
        params.put("fileOriginName", contractFile.getOriginalFilename());
        params.put("annexGroupName", annexInfo[0]);
        params.put("annexName", annexInfo[1]);
        params.put("annexOriginName", annexFile.getOriginalFilename());
        log.info("保存合同信息的参数：" + params.toString());
        return service.saveContractInfo(params);
    }

    @PostMapping("/modifyContractInfo")
    @ApiOperation(value = "修改合同信息", httpMethod = "POST")
    public ResultModel modifyContractInfo(String contractId, String deadline, String contractName, String contractTypeDropdownParam, MultipartFile contractFile,
                                          MultipartFile annexFile, HttpSession session) throws IOException, ParseException {
        ResultModel model = new ResultModel();
        ContractInfoBean contractInfo = contractInfoRepository.findById(contractId).get();

        String[] fileInfo = null;
        String[] annexInfo = null;
        try {
            // 0代表删除成功
            int status = fastdfsClientService.delete(contractInfo.getFileGroupName(), contractInfo.getFileName());
            log.info("合同文件删除状态：" + status);
            fileInfo = fastdfsClientService.autoUpload(contractFile.getBytes(), "doc");
            log.info("fastdfs合同文件存储的分组名：" + fileInfo[0]);
            log.info("fastdfs合同文件存储的文件ID：" + fileInfo[1]);
        } catch (Exception e) {
            model.setStatusCode(ReturnStatusCode.FASTDFS_FILE_ERROR);
            model.setResultMessage(ReturnStatusCode.FASTDFS_FILE_ERROR_MESSAGE);
            log.info("fastdfs合同文件存储失败！");
            return model;
        }
        try {
            // 0代表删除成功
            int status = fastdfsClientService.delete(contractInfo.getAnnexGroupName(), contractInfo.getAnnexName());
            log.info("合同附件删除状态：" + status);
            annexInfo = fastdfsClientService.autoUpload(annexFile.getBytes(), "zip");
            log.info("fastdfs合同附件存储的分组名：" + annexInfo[0]);
            log.info("fastdfs合同附件存储的文件ID：" + annexInfo[1]);
        } catch (Exception e) {
            model.setStatusCode(ReturnStatusCode.FASTDFS_ANNEX_ERROR);
            model.setResultMessage(ReturnStatusCode.FASTDFS_ANNEX_ERROR_MESSAGE);
            log.info("fastdfs合同附件存储文件失败！");
            return model;
        }

        AccountInfoBean accountInfo = (AccountInfoBean) session.getAttribute("currentAccountInfo");
        StaffInfoBean staffInfo = (StaffInfoBean) session.getAttribute("currentStaffInfo");
        String uuid = contractId;
        String contractStatus = ConstantDataType.CONTRACT_ACTIVE_STATUS;
        LocalDateTime currentDateTime = PropertyUtil.getCurrentDateTime();
        String contractText = "";
        try {
            Document document = new Document();
            document.loadFromStream(contractFile.getInputStream(), FileFormat.Docx);
            contractText = document.getText();
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.DOC_EXTRACT_ERROR);
            model.setResultMessage(ReturnStatusCode.DOC_EXTRACT_ERROR_MESSAGE);
            log.info("doc文件解析失败---程序执行失败！");
            return model;
        }

        try {
            contractEsBeanRepository.deleteById(contractId);
            ContractEsBean contractEsBean = new ContractEsBean(uuid, contractName, contractStatus, contractText, staffInfo.getDepartName(), contractTypeDropdownParam,
                    staffInfo.getStaffCode(), staffInfo.getStaffName(), staffInfo.getDepartId(), LocalDateTimeUtil.getStringByLocalDateTime(currentDateTime));
            log.info("ES存储的对象信息为：" + contractEsBean.toString());
            contractEsBeanRepository.save(contractEsBean);
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ES_SAVE_ERROR);
            model.setResultMessage(ReturnStatusCode.ES_SAVE_ERROR_MESSAGE);
            log.info("ES存储合同信息失败---程序执行失败！");
            return model;
        }

        String contractTypeDropdown = contractTypeDropdownParam;
        if ("-1".equals(contractTypeDropdownParam)) {
            contractTypeDropdown = "";
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("contractName", contractName);
        params.put("deadline", deadline);
        params.put("contractTypeDropdownParam", contractTypeDropdown);
        params.put("contractStatus", contractStatus);
        params.put("accountCode", accountInfo.getAccountCode());
        params.put("staffCode", staffInfo.getStaffCode());
        params.put("staffName", staffInfo.getStaffName());
        params.put("departId", staffInfo.getDepartId());
        params.put("departName", staffInfo.getDepartName());
        params.put("fileGroupName", fileInfo[0]);
        params.put("fileName", fileInfo[1]);
        params.put("fileOriginName", contractFile.getOriginalFilename());
        params.put("annexGroupName", annexInfo[0]);
        params.put("annexName", annexInfo[1]);
        params.put("annexOriginName", annexFile.getOriginalFilename());
        log.info("修改合同信息的参数：" + params.toString());
        return service.saveContractInfo(params);
    }


    @PostMapping("/deleteContractInfo")
    @ApiOperation(value = "删除合同信息", httpMethod = "POST")
    public ResultModel deleteContractInfo(String contractId) {
        ResultModel model = new ResultModel();
        try {
            log.info("ES删除的合同信息的id为：" + contractId);
            contractEsBeanRepository.deleteById(contractId);
        } catch (Exception e) {
            e.printStackTrace();
            model.setStatusCode(ReturnStatusCode.ES_DELETE_ERROR);
            model.setResultMessage(ReturnStatusCode.ES_DELETE_ERROR_MESSAGE);
            log.info("ES删除合同信息失败---程序执行失败！");
            return model;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("contractId", contractId);
        log.info("删除合同信息的参数：" + params.toString());
        return service.deleteContractInfo(params);
    }

}
